import 'dart:convert';

import 'package:fast_gbk/fast_gbk.dart';
import 'package:wch/utils/log_utils.dart';

class EndianUtils {
  static Encoding utf8Coding = utf8;
  static Encoding asciiCoding = ascii;
  static Encoding gbkCoding = gbk;
  static List<int> getBytes(String src, Encoding encoding) {
    return encoding.encode(src);
  }

  static List<int> getBytesFixLen(String src, Encoding encoding, int destLen) {
    List<int> encodeList = gbk.encode(src); // 使用 utf8 编码获取源字符串的字节列表
    List<int> destList = [];
    destList.addAll(encodeList);
    int index = destList.length;
    while (index < destLen) {
      destList.add(32); // 添加空格字节，ASCII 码中 32 代表空格
      index++;
    }

    return destList;
  }

  static List<int> toBytesFromNumStr(String numStr) {
    int len = numStr.length % 2 == 0 ? numStr.length ~/ 2 : numStr.length ~/ 2 + 1;

    List<int> array = List<int>.filled(len, 0);
    int condition = 0;
    int index = 0;

    while (condition < numStr.length) {
      int length = (numStr.length - condition) > 1 ? 2 : 1;
      String s = numStr.substring(condition, condition + length);
      int value = int.parse(s);

      array[index] = value;

      condition += length;
      index++;
    }

    return array;
  }

  static String byteToAsciiString(List<int> b, int start, int length) {
    if (b == null) return '';
    if (b.length < (start + length)) return '';
    List<int> bytes = b.sublist(start, start + length);
    try {
      return gbk.decode(bytes);
    } catch (e) {
      LogUtils.log(e.toString());
      return String.fromCharCodes(bytes);
    }
  }
}